<template>
  <!-- 肥药双减统计 -->
  <BaseMainSlot>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="28"
        :has-add="false"
        :has-del="false"
        :has-edit="false"
        :has-cancel="false"
        :has-edit-column="true"
        @showColumn="showColumn"
      />
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading"
        :listData="tableData" :showSelectColumn="false">
        <template v-slot:assetQuantity="{ row }">
          <template v-if="!row.index">
            <div v-if="row.average">
              {{ row.assetQuantity }}{{ row.unitName }}
            </div>
            <div v-else>—</div>
          </template>
        </template>
        <template v-slot:materialTypeName="{ row, item }">
          <template v-if="!row.index">
            {{ row.materialDTO ? row.materialDTO[item.prop] : '' }}
          </template>
        </template>
        <template v-slot:batchName="{ row, item }">
          <template v-if="!row.index">
            {{ row.productionBatchBO ? row.productionBatchBO[item.prop] : '' }}
          </template>
        </template>
        <template v-slot:average="{ row }">
          <template v-if="!row.index">
            {{ row.assetQuantity }}{{ row.unitName }}
          </template>
        </template>
        <template v-slot:ratedQuantity="{ row }">
          <template v-if="!row.index && row.materialDTO">
            <div v-if="row.materialDTO.ratedQuantity">
              {{ row.materialDTO.ratedQuantity
              }}{{ row.materialDTO.unitName }} <span>/</span> {{ '亩' }}
            </div>
            <div v-else>—</div>
          </template>
        </template>
        <template v-slot:agricult="{ row }">
          <template v-if="!row.index && row.agricult">
            <div
              v-if="row.agricult"
              :class="
                row.agricult === '超出定额用量' ? 'agricult' : 'agrigreen'
              "
            >
              {{ row.agricult }}
            </div>
            <div v-else>—</div>
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        id="tableColumnDialog"
        title="配置列"
        :visible.sync="dialogTableColumnVisible"
      >
        <tableColumn
          v-if="dialogTableColumnVisible"
          ref="tableColumn"
          :tableColumn="allTableColumn"
          @cancelColumn="cancelColumn"
        />
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="dialogTableColumnVisible = false">
            取 消
          </el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="saveColumn"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
// import managementtwo from "@/api/basic-info-manage/agr-source-base-Manage/index";
import managementtwo from "@/api/digital-production/agr-input-management/agr-input-managementtwo";
// import danwei from "@/api/basic-info-manage/unit-manage/index";
// import nowpagereq from "@/api/basic-info-manage/agr-source-base-Manage/index";
import nowstaff from "@/api/digital-operation/personnel-cost-mansge/staff-manage/index";
import userreq from "@/api/user/index";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import { mymixin } from "@/utils/mixin";
// import { getToken } from '@/utils/auth';
export default {
  name: "FertilizerStatisticsQuery",
  components: { SearchForm, Table, ActionBar, Pagination, BaseMainSlot },
  mixins: [mymixin],
  data() {
    return {
      tableColumn: [
        { prop: 'materialTypeName', label: '药肥种类', slotName: 'materialTypeName' },
        { prop: 'batchName', label: '投入批次', minWidth: '150', slotName: 'batchName' },
        { prop: 'personName', label: '经手人' },
        { prop: 'assetQuantity', label: '总投入量', slotName: 'assetQuantity' },
        { prop: 'average', label: '亩均用量', slotName: 'average' },
        { prop: 'ratedQuantity', label: '定额用量', slotName: 'ratedQuantity' },
        { prop: 'agricult', label: '是否超标', slotName: 'agricult' },
      ],
      formConfig: [
        {
          label: '批次名称',
          prop: 'batchNo',
          type: 'select',
          options: [], // batchList
          optionKey: { label: 'batchName', value: 'batchNo' },
        }, {
          label: '设施名称',
          prop: 'facilityNo',
          type: 'select',
          options: [], // facilityList
          optionKey: { label: 'facilityName', value: 'facilityNo' }
        }, {
          label: '农资名称',
          prop: 'materialNo',
          type: 'select',
          options: [], // queryagriculturalMaterialList
          optionKey: { label: 'materialName', value: 'materialNo' },
        }, {
          label: '经手人',
          prop: 'personNo',
          type: 'select',
          options: [], // StaffList
          optionKey: { label: 'personName', value: 'personNo' }
        }, {
          label: '选择时间',
          prop: 'date',
          type: 'daterange',
        },
      ],
      agriculturalMaterialNameLike: "", // 品种名称模糊查询
      // 单位选择列表
      unitlist: [],
      // 农资选择列表
      agrSourseTypeList: [],
      // 已选择的农资列表
      selectnozilist: [],
      agriculturalMaterialTypeName: "",
      // 校验规则
      //   rules: {},
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      nowselectedList: [],
      // 农资图片
      imgUrl: "",
      // 搜索提交
      searchlist: {},
      batchNo: "",
      facilityNo: "",
      materialNo: "",
      // 批次
      batchList: [],
      // 设施
      facilityList: [],
      facilityAList: [],
      // 农资名称
      agriculturalMaterialList: [],
      queryagriculturalMaterialList: [],
      // 员工
      staffList: [],
      StaffList: [],
      personNo: ""
    };
  },
  watch: {
    nowChanceStau(newval) {
      // 当状态为删除的时候触发删除方法---另外的删除修改添加，通过点击保存，调用方法来实现
      if (newval === "add") {
        this.selectnozilist = [];
        this.agriculturalMaterialTypeName = "";
      }
    }
  },
  mounted() {
    this.getselectmessage();
    this.getTableDataList();
  },
  methods: {
    // 获取当前表格信息
    getTableDataList() {
      this.loading = true;
      this.tableData = [];
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
        entity: {
          batchNo: this.searchlist.batchNo,
          facilityNo: this.searchlist.facilityNo,
          startTime: this.searchlist.date && this.searchlist.date[0],
          endTime: this.searchlist.date && this.searchlist.date[1],
          materialNo: this.searchlist.materialNo,
          personNo: this.searchlist.personNo,
          farmingTypeNo: sessionStorage.farmingTypeNo,
          organizationNo: sessionStorage.organizationNo,
          medicinalFertilizerSign: true
        }
      };
      this.entity = params.entity
      managementtwo.getMaterialInputList(params).then((res) => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error("当前农业类型表格获取失败");
        }
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
        this.tableData.forEach((item) => {
          if (item.average > item.materialDTO.ratedQuantity) {
            item.agricult = "超出定额用量";
          } else {
            item.agricult = "未超出定额用量";
          }
        });
        // console.log(this.tableData)
        this.addblankmet();
        this.resetActionBar();
      });
    },
    // 获取下拉数据
    getselectmessage() {
      // // 获取单位选择框数据
      // danwei.getallunitlist().then((res) => {
      //   this.unitlist = res.data;
      // });
      // let params = {
      // page: this.currentPage,
      // size: this.pageSize
      // };
      // 获取批次选择框数据
      managementtwo.queryBatchListName().then((res) => {
        this.batchList = res.data;
        this.formConfig[0].options = res.data;
      });
      nowstaff.getStaffListByCondition().then(res => {
        this.StaffList = res.data;
        this.formConfig[3].options = res.data.map(el => {
          return { ...el, personName: el.person?.name }
        });
      });
      // 获取设施选择框数据
      // managementtwo.queryFacilityListName().then((res) => {
      //   this.facilityList = res.data;
      // });
      let faciparams = {};
      if (this.nowChanceStau === "add") {
        faciparams = {
          organizationList: sessionStorage
            .getItem("organizationList")
            .split(","),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
          facilityStatus: 1
        };
      } else {
        faciparams = {
          organizationList: sessionStorage
            .getItem("organizationList")
            .split(",")
            .concat([sessionStorage.parentId || ""]),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo")
        };
      }
      userreq.getfacilityAll(faciparams).then((res) => {
        this.facilityList = res.data;
        this.formConfig[1].options = res.data;
      });
      managementtwo.queryFacilityName().then((res) => {
        this.facilityAList = res.data;
      });
      managementtwo.getqueryList().then((res) => {
        this.queryagriculturalMaterialList = res.data;
        this.formConfig[2].options = res.data;
      });
      // // 获取农资下拉内容
      // nowpagereq.getqueryList().then((res) => {
      //   let data = res.data;
      //   // 赋值总条数
      //   // this.totalSize = data.totalElements;
      //   // 赋值数组
      //   this.agriculturalMaterialList = data.content;
      // });
    },
    // 农资数据处理掉空child
    // 循环过滤树形数组
    filterArrForKey(arr) {
      let newArr = [];
      newArr = arr.map((item) => {
        if (item.child.length > 0) {
          item = {
            ...item,
            child: this.filterArrForKey(item.child)
          };
        } else {
          delete item.child;
        }
        return item;
      });
      newArr = newArr.filter((item) => item != null);
      return newArr;
    },
    cascaderChange(e) {
      // console.log(e);
    },
    uploadimage(e) {
      // console.log(e);
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // 表格点击
    handleEdit(list) {
      this.formData = list;
      // let testname = list.agriculturalMaterialType;
      // this.selectnozilist = [];
      // if (testname) {
      //   this.agriculturalMaterialTypeName =
      //     testname.agriculturalMaterialTypeName;
      // } else {
      //   this.agriculturalMaterialTypeName = "";
      // }

      // this.editActive = true;
    },
    handleSelectionChange(list) {
      this.nowselectedList = [];
      this.nowselectedList = list.map((item) => {
        return item.materialNo;
      });
      if (this.nowselectedList && this.nowselectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    delmessage() {
      if (this.nowChanceStau === "del") {
        managementtwo.delmeslist(this.nowselectedList).then((res) => {
          if (res.code === 1) {
            this.getTableDataList();
            this.$message.success("删除成功");
          } else {
            this.$message.error("删除失败");
          }
        });
      }
    },
    save() {
      this.$refs["formData"].validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "add") {
            let parone = {
              ...this.formData,
              agriculturalMaterialTypeId:
                this.selectnozilist[this.selectnozilist.length - 1]
            };
            // this.batchList.forEach(
            //   item => {
            //     if (item.batchNo === parone.batchNo) {
            //       parone.organizationNo = item.organizationNo || "批次暂无组织结构id"
            //     }
            //   }
            // )
            managementtwo.addmeslist(parone).then((res) => {
              if (res.code === 1) {
                this.getTableDataList();
                this.$message.success("添加成功");
              } else {
                this.$message.error("添加失败");
              }
            });
          }
          if (this.nowChanceStau === "edit") {
            let params = this.formData;
            delete params["agriculturalMaterialType"];
            if (this.selectnozilist === []) {
              //   console.log("")
            } else {
              delete params["agriculturalMaterialTypeName"];
              params["agriculturalMaterialTypeId"] =
                this.selectnozilist[this.selectnozilist.length - 1];
            }
            managementtwo.editmeslist(params).then((res) => {
              if (res.code === 1) {
                this.getTableDataList();
                this.$message.success("修改成功");
              } else {
                this.$message.error("修改失败");
              }
            });
          }
        } else {
          this.$message.warning("请填写完整信息！！");
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.zhtabletitle {
  color: #31f7dd;
  margin-bottom: 10px;
}
::v-deep .staff-manage .common-layout .content {
  overflow-y: auto;
}
.upimg {
  ::v-deep .xunzeimage {
    width: 140px !important;
  }
}
.agricult {
  color: #ff0000;
}
.agrigreen {
  color: #008000;
}
</style>
